<template>
  <div class="module1">
    <!-- 操作栏：排序、搜索、刷新 -->
    <div style="height: 100%;">
      <div class="header-container">
        <ListTitle list-title="空域使用规范管理"></ListTitle>

        <div v-if="!visible" class="search-from">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
            <!-- 排序下拉框 -->
            <el-form-item :key="'order'" label="">
              <div class="sort-wrapper">
                <el-select v-model="order" placeholder="选择排序方式" clearable>
                  <el-option label="时间最新" value="时间最新"></el-option>
                  <el-option label="时间最晚" value="时间最晚"></el-option>
                </el-select>

                <!-- 自定义图片按钮，点击触发排序 -->
                <button class="native-action-button" type="button" @click="timesearch">
                  <img src="@/assets/img/module1/page1img2.png" alt="操作按钮图标" />
                </button>
              </div>
            </el-form-item>

            <!-- 类别搜索框 -->
            <el-form-item :key="'category'" label="类别">
              <el-select v-model="category" placeholder="全部" clearable>
                <el-option label="政策法规" value="0"></el-option>
                <el-option label="通知公告" value="1"></el-option>
                <el-option label="批复文件" value="2"></el-option>
              </el-select>
            </el-form-item>

            <!-- 来源搜索框 -->
            <el-form-item :key="'source'" label="来源">
              <el-select v-model="source" placeholder="全部" clearable>
                <!-- <el-option label="地方政府" value="0"></el-option>
                <el-option label="UOM" value="2"></el-option>
                <el-option label="民航" value="1"></el-option> -->
                <el-option label="交通运输部" value="交通运输部"></el-option>
                <el-option label="中国民用航空局" value="中国民用航空局"></el-option>
                <el-option label="国家空管委" value="国家空管委国家空管委"></el-option>
                <el-option label="国家市场监督管理总局" value="国家市场监督管理总局"></el-option>
                <el-option label="中华人民共和国中央人民政府" value="中华人民共和国中央人民政府"></el-option>
                <el-option label="UOM" value="UOM"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item :key="'searchKeyword'">
              <el-input v-model="searchKeyword" placeholder="请输入关键字" clearable />
            </el-form-item>


            <!-- 提交和重置按钮 -->
            <el-form-item>
              <el-button size="mini" @click="resetQuery">重置</el-button>
              <el-button type="primary" size="mini" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>

          <div class="refresh-wrapper">
            <!-- 文件库导入 -->
            <el-button type="primary" size="mini" @click="isFileLibraryVisible = true">
              文件库导入
            </el-button>
            <!-- 大语言模型 -->
            <el-button type="primary" size="mini" @click="openChatModule">
              智能查询
            </el-button>
            <!-- 发布按钮 -->
            <el-button type="primary" size="mini" @click="handlePublish" :disabled="selectedRows.length === 0">
              发布
            </el-button>
            <!-- 刷新按钮 (Element UI) -->
            <el-button type="primary" icon="el-icon-refresh" class="el-refresh-button" size="mini"
              @click="refresh">刷新</el-button>
          </div>
        </div>
        <!-- 表格展示 -->
        <div v-if="!visible" class="body-container">
          <div class="regional_table">
            <!-- el-table 表格 -->
            <el-table :data="tableData1" style="width: 100%; height: 100%;max-width:calc(100vw - 0px);"
              :max-height="tableMaxHeight" empty-text="暂无数据" @selection-change="handleSelectionChange">
              <!-- 复选框 -->
              <el-table-column type="selection" width="60"></el-table-column>
              <el-table-column label="#" :min-width="50" :max-width="100" width="55">
                <!-- scope 中的信息是从传递给 el-table 的 tableData1 中来的，每一行的数据通过 scope.row 可以被访问到。 -->
                <template #default="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column label="文件名称" :min-width="120" :max-width="200">
                <template #default="scope">
                  {{ scope.row.title }}
                </template>
              </el-table-column>
              <!-- 动态渲染列 -->
              <!-- <el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop" :label="column.label" :min-width="column.width"
              > -->
              <el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop"
                :label="column.label" :min-width="column.width">
              </el-table-column>
              <!-- 操作栏 -->
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <button @click="handleView(scope.row)" class="view-button">查看</button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagenation">
              <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
              </el-pagination>
            </div>
          </div>
        </div>

        <CustomDialog2 :visible.sync="visible" :title="title1" :selectedrow="selectedRow" :tabledata="tableData1"
          :row="row">
        </CustomDialog2>

        <!-- 大语言模型对话模块，右下角显示 -->
        <ChatModule v-if="isChatVisible" @close="closeChatModule" />


        <!-- 文件库导入弹窗 -->
        <CustomDialogFileAdd :visible.sync="isFileLibraryVisible" @import-success="refresh">
        </CustomDialogFileAdd>
      </div>
    </div>
  </div>
</template>

<script>
import ListTitle from "@/components/ListTitle";
import CustomDialog2 from '@/components/CustomDialog-lin.vue';
import ChatModule from '@/components/ChatModule.vue'; // 引入大语言模型对话模块
import CustomDialogFileAdd from '@/components/CustomDialogModule1FileAdd.vue'
import axios from 'axios';

const baseApi = process.env.NODE_ENV === 'production'
  //? process.env.VUE_APP_REMOTE_API
  ? '/api'  // 使用代理路径
  : process.env.VUE_APP_REMOTE_API_MODULE1;

export default {
  name: "Module1AirspaceRegulations",
  components: {
    CustomDialog2,
    CustomDialogFileAdd,
    ListTitle,
    ChatModule
  },
  data() {
    return {
      tableData1: [],
      tableColumns: [
        // { prop: 'id', label: '#' },
        // { prop: 'title', label: '文件名称' },
        { prop: 'publicationTime', label: '接收时间', width: '90%' }, // 使用slot来显示带图标的列
        { prop: 'versionNumber', label: '版本' },
        { prop: 'informationCategory', label: '信息类别' },
        { prop: 'informationSource', label: '信息来源' },
      ],
      title1: '',
      row: '',
      visible: false, // 控制弹窗显示状态
      selectedRow: '',
      currentPage: 1, // 当前页
      pageSize: 20, // 每页显示条数
      total: 0, // 总条数
      selectedRows: [], // 存储选中的行
      order: '时间最新',
      keytext: '',
      category: '',
      source: '',
      searchKeyword: '',
      informationData: [],
      usingStandards: '', // 使用规范内容
      constraintInformation: '', // 约束条件
      isFocused: false, // 用来控制输入框是否获得焦点
      tableMaxHeight: 200,
      queryParams: {  // 初始化 queryParams 对象
        order: '',
        category: '',
        source: '',
        searchKeyword: ''
      },
      isChatVisible: false, // 控制大语言模型对话模块的显示与隐藏
      isFileLibraryVisible: false, // 控制“文件库导入”弹窗显隐
    };
  },
  created() {
    this.calculateTableHeight();
    console.log('页面接收到的数据:', this.tableData1);
    console.log('父组件 selectedRow:', this.selectedRow);
  },
  watch: {
    // 监听文件库弹窗关闭事件，关闭时刷新数据
    isFileLibraryVisible(newVal, oldVal) {
      // newVal：当前状态（false=关闭），oldVal：上一个状态（true=显示）
      if (!newVal && oldVal) {
        this.refresh(); // 弹窗关闭时刷新数据
      }
    }
  },
  methods: {
    // 打开大语言模型对话模块
    openChatModule() {
      this.isChatVisible = true;
    },
    // 关闭大语言模型对话模块
    closeChatModule() {
      this.isChatVisible = false;
    },
    // 处理选中的行
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    // 发布逻辑
    async handlePublish() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要发布的项！");
        return;
      }

      try {
        const payload = this.selectedRows.map(item => ({ id: item.id, title: item.title }));

        // 模拟请求
        await new Promise(resolve => setTimeout(resolve, 1500));

        this.$message.success("选中的项已成功发布！");
        console.log("发布数据：", payload);
        this.selectedRows = [];
      } catch (error) {
        this.$message.error("发布失败，请稍后重试！");
      }
    },
    calculateTableHeight() {
      const windowHeight = window.innerHeight;
      this.tableMaxHeight = windowHeight * 0.7;
      console.log("此时的tableMaxHeight", this.tableMaxHeight)
    },
    // 刷新数据：重新获取空域规范列表
    async refresh() {
      console.log("导入数据库弹窗关闭，触发数据刷新");
      await this.fetchAirspaceDemand(); // 核心：重新调用数据接口
      console.log('页面刷新后的数据:', this.tableData1);
    },
    async fetchAirspaceDemand() {
      try {
        const params = {
          currentPage: this.currentPage,
          size: this.pageSize,
          order: this.order,
          title: this.keytext,
          informationCategory: this.category,
          informationSources: this.source === "" ? null : this.source
        };
        console.log("页面2发给后端的数据", params);

        const response = await axios.post(`${baseApi}/admin/airspaceNormsAndConstraints/keywordSearch`, params);

        this.total = response.data.data.total;

        const convertedData = response.data.data.pageData.map((item, index) => {
          return {
            // 生成序号 (id) 字段，基于当前页和每页条数
            id: this.pageSize * (this.currentPage - 1) + index + 1,
            realId: item.id,
            title: item.title,

            // 处理 applicationAcceptanceTime 字段
            publicationTime: (() => {
              const date = new Date(item.publicationTime);
              const year = date.getFullYear();
              const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
              const day = String(date.getDate()).padStart(2, '0');
              const hours = String(date.getHours()).padStart(2, '0');
              const minutes = String(date.getMinutes()).padStart(2, '0');
              const seconds = String(date.getSeconds()).padStart(2, '0');

              return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
            })(),

            // 处理 informationCategory 字段
            informationCategory: item.informationCategory === 1 ? '通知公告' :
              item.informationCategory === 0 ? '政策法规' :
                item.informationCategory === 2 ? '批复文件' :
                  '未知',


            // 处理 informationSource 字段
            // informationSource: item.informationSource === 0 ? '地方政府' :
            //   (item.informationSource === 1 ? '民航' : 'UOM')
            informationSource: item.informationSources,
            // 添加版本号字段
            versionNumber: item.versionNumber,
          };
        });

        this.tableData1 = convertedData;
        console.log("airspaceDemand接口返回的数据", response);
      } catch (error) {
        console.error('Error fetching airspace demand:', error);
      }
    },

    //时间查询按钮
    async timesearch() {
      await this.fetchAirspaceDemand();
    },
    //文件名称查询按钮
    async handleSearch() {
      this.keytext = this.searchKeyword;
      await this.fetchAirspaceDemand();
    },
    //查看按钮
    async handleView(row) {
      // this.selectedRow = row.id;
      this.selectedRow = row.realId;
      this.visible = true;
      this.title1 = row.title;
      this.row = row;
      console.log('父组件点击了行的title:', row.title);
      console.log('父组件点击了行的title:', this.title1);
      console.log('父组件 selectedRow:', this.selectedRow);
      console.log('使用规范:', this.usingStandards);
      console.log('约束信息:', this.constraintInformation);
    },
    async resetQuery() {
      // 初始化 queryParams 对象
      this.currentPage = 1;
      this.size = 10;
      this.order = '时间最新';
      this.keytext = '';
      this.searchKeyword = '';
      this.category = '';
      this.source = '';

      await this.fetchAirspaceDemand();
    },
    //刷新
    async refresh() {
      await this.fetchAirspaceDemand();
      console.log('页面刷新后的数据:', this.tableData1);
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchAirspaceDemand(); // 当页大小改变时重新获取数据
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchAirspaceDemand(); // 当当前页改变时重新获取数据
    },
  },
  mounted() {
    this.fetchAirspaceDemand();
  }
};
</script>
<style lang="scss" scoped>
@import "../assets/demo/index.scss";
</style>
<style scoped>
.module1 {
  height: 100%;
}

/* 顶部容器样式 */
.header-container {
  width: 100%;
  /* 占据整个宽度 */
  position: relative;
  /* 定位为相对页面顶部 */
  top: 0;
  left: 0;
}

/* 顶部内容区样式 */
.header-content {
  position: relative;
  width: 100%;
  /* 使其占据整个宽度 */
  /* height: 10%; */
  background: url("../assets/img/module1/page1top.png") no-repeat;
  background-size: cover;
  display: flex;
  align-items: center;
  /* 垂直居中 */
  /* padding: 5px; */
  /* 增加内部间距 */
}

/* 标题样式 */
.header-title {
  background-image: linear-gradient(180deg, rgba(200, 215, 228, 1) 0, rgba(255, 255, 255, 1) 100%);
  position: relative;
  flex: 2;
  margin-left: 5%;
  width: 20%;
  height: 20%;
  color: rgba(112, 112, 112, 1);
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 1px;
  font-family: PangMenZhengDao-3;
  text-align: left;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 图标样式 */
.header-icon {
  position: relative;
  width: 22px;
  height: 20px;
  margin-left: 20px;
  /* 与其他内容间隔 */
  margin-top: -20px;
}

/*隐藏el-table的滚动条*/
/* 隐藏 el-table 的滚动条 */
.regional_table /deep/ .el-table__body-wrapper {
  overflow-y: auto;
  /* 保持内容滚动 */
  height: 75vh;
}


.regional_table /deep/ .el-table__body-wrapper::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条 (Chrome/Safari) */
}

.regional_table /deep/ .el-table__body-wrapper {
  scrollbar-width: none;
  /* 隐藏滚动条 (Firefox) */
}

/* 操作栏容器 */
.operation-bar {
  display: flex;
  align-items: center;
  width: 100%;
  height: 4vh;
  /* 调整高度为合适的视口高度 */
  padding: 1vh 0vw;
  /* 使用视口单位的内边距 */
}

/* 操作按钮 */
.sort-wrapper {
  display: flex;
  align-items: center;
}

.native-action-button {
  border: none;
  cursor: pointer;
  background-color: transparent;
  margin-left: 10px;
  padding: 0;
  width: 24px;
  height: 24px;
}


/* 下拉框部分 (原生下拉框) */
.dropdown-wrapper {
  width: 10%;
}

.dropdown-native {
  width: 100%;
  padding: 0.5vh;
  font-size: 2vh;
  background-color: transparent;
  border: 1px solid #ccc;
  border-radius: 4px;
  color: #fff;
}

.selectOption {
  color: #ffffff;
  background-color: #11202C;
}

/* 操作按钮 */
.native-action-button {
  display: flex;
  align-items: center;
  border: none;
  border-radius: 5px;
  font-size: 2vh;
  cursor: pointer;
  /* margin-right: 1vw; */
  background-color: transparent;
}

.native-action-button img {
  width: 100%;
  height: auto;
}

/* 名称搜索框部分 */
.search-wrapper {
  width: 10%;
  margin-right: 1.5vw;
  font-size: 2vh;
}

/* 信息类别搜索框部分 */
.dropdown-wrapper1 {
  width: 10%;
  margin-right: 1vw;
}

.dropdown-native1 {
  width: 100%;
  padding: 0.5vh;
  font-size: 2vh;
  background-color: transparent;
  border: 1px solid #ccc;
  border-radius: 4px;
  color: #fff;
}

.dropdown-wrapper2 {
  width: 10%;
  margin-right: 1vw;
}

.dropdown-native2 {
  width: 100%;
  padding: 0.5vh;
  font-size: 2vh;
  background-color: transparent;
  border: 1px solid #ccc;
  border-radius: 4px;
  color: #fff;
}

.search-input::placeholder {
  color: white !important;
  opacity: 1;
}

.search-input {
  width: 100%;
  padding: 0.5vh;
  font-size: 2vh;
  background-color: transparent;
  border: 1px solid #ccc;
  border-radius: 4px;
  color: #fff;
}

/* 查询按钮样式 */
.el-query-button {
  font-size: 2vh;
  padding: 0.5vh 1vw;
  margin-right: 2vw;
}

.refresh-wrapper {
  margin-left: auto;
}

/* 刷新按钮样式 */
.el-refresh-button {
  margin-right: 2.1rem;
  width: 107.5px;
}

.view-button {
  background: transparent;
  /* 背景透明 */
  border: none;
  /* 去掉默认按钮边框 */
  color: #648bf4;
  /* 深蓝色字体 */
  font-size: 14px;
  /* 字体大小 */
  cursor: pointer;
  /* 鼠标悬停时显示手型 */
}

.view-button:hover {
  text-decoration: underline;
  /* 悬停时下划线 */
}


.body-container {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  width: 99%;
  height: 99%;
  padding: 1vh 1vw 1vh 0;
}

.regional_table {
  overflow-y: auto;
  /* 超出时垂直滚动 */
  height: 75vh;

}

/* 隐藏滚动条 - Webkit浏览器（Chrome, Safari等） */
.regional_table::-webkit-scrollbar {
  width: 0;
  height: 0;
}



/* 最外层透明表格背景与白色字体 */
.regional_table /deep/ .el-table,
.regional_table /deep/ .el-table__expanded-cell {
  background-color: transparent;
  /* 设置透明背景 */
  color: white;
  /* 表格文字颜色 */

}

/* 表格头部和单元格的背景颜色透明 */
.regional_table /deep/ .el-table th,
.regional_table /deep/ .el-table tr,
.regional_table /deep/ .el-table td {
  background-color: transparent !important;
  color: rgb(216, 208, 208);
  ;
  /* font-size: 0.9rem; */
}

/* 设置表格边框 */
.regional_table /deep/ .el-table__body-wrapper {
  border: 0.5px solid transparent;
  /* 边框为白色 */
}

/* 如果表头或其他部分需要特殊透明处理 */
.regional_table /deep/ .el-table__header-wrapper {
  background-color: rgba(255, 255, 255, 0.1);
  /* 表头轻微透明 */
}

.regional_table /deep/ .el-table .el-table__cell {
  padding: 0.3rem;
  /* height:2.5rem; */

}


/* pagenation */
.pagenation {
  height: 10%;
  margin-top: 1rem;
  float: right;
}

.regional_table /deep/ .el-pagination.is-background .el-pager li {
  background: transparent;
  color: #a09292;
}

.regional_table /deep/ .el-pagination.is-background .btn-prev {
  background: transparent;
}

.regional_table /deep/ .el-input__inner {
  background-color: transparent;
  color: #fff;
}
</style>

<style lang="scss" scoped>
@import "../assets/demo/index.scss";
</style>